# -*- coding: utf-8 -*-
# @Date：2024/10/4 21:13:16
# @Author：CJiaの青姝
# @FileName：log
# @Editor：PyCharm2024
# @Remark：
from typing import List

from application.models import AppLog
from ninja import Router, Field, Query, ModelSchema
from ninja.pagination import paginate

from utils.cj_ninja import CjFilters, MyPagination
from utils.cj_crud import delete, retrieve
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class Filters(CjFilters):
    app_id: int = Field(None, description="应用id", alias='app_id')
    appName: str = Field(None, description="应用名称", alias='appName')
    create_time: str = Field(None, description="应用日志创建时间", alias='create_time')

    class Config:
        title = "应用日志查询参数"


class AppLogSchemaIn(ModelSchema):
    app_id: int = Field(None, description="应用id", alias="id")
    uniAppId: str = Field(None, description="应用标识AppID", alias="appId")
    uniAppRemark: str = Field(None, description="应用标识备注", alias="remark")
    appVersionName: str = Field(None, description="应用版本名称", alias="appVersion")
    systemName: str = Field(None, description="设备", alias="system")
    brand: str = Field(None, description="品牌", alias="model")

    class Config:
        title = '创建应用日志参数'
        model = AppLog
        model_exclude = ['id', 'status', 'create_time', 'update_time', 'app']


class AppLogSchemaOut(ModelSchema):
    class Config:
        title = '应用日志对象实例'
        model = AppLog
        model_fields = "__all__"


@router.post("/appLog/add", auth=None, response=AppLogSchemaOut, summary="创建应用日志")
def create_app_log(request, data: AppLogSchemaIn) -> SuccessResponse | ErrorResponse:
    """ 创建应用日志 """
    # 转换数据
    data = data.dict()
    # 保存日志
    result = AppLog.objects.create(**data)
    # 返回结果
    return result


@router.delete("/appLog/del/{uuid}", response=AppLogSchemaOut, summary="删除应用日志")
def delete_app_log(request, uuid: int):
    """ 删除应用日志 """
    # 调用删除方法
    result, code = delete(AppLog, uuid)
    if code != 200:
        return ErrorResponse(code=code, msg=result)
    # 返回结果
    return SuccessResponse(data=result, msg="删除成功")


@router.get("/appLog/listPage", response=List[AppLogSchemaOut], summary="获取分页应用日志列表")
@paginate(MyPagination)
def list_app_logs(request, filters: Filters = Query(...)):
    """ 获取分页应用日志列表 """
    # 获取分页列表
    result = retrieve(request, AppLog, [], filters)
    # 返回结果
    return result
